package com.chinaoly.baotou.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置
 *
 * @author
 * @date 2020-12-09 10:43:39
 */
@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Bean
    public Retryer feignRetryer() {
        // period=100 发起当前请求的时间间隔，单位毫秒
        // maxPeriod=1000 发起当前请求的最大时间间隔，单位毫秒TimeUnit.SECONDS.toMillis(30000)
        // maxAttempts=5 最多请求次数，包括第一次
        return new Retryer.Default(10000, 20000, 5);
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
        }
    }

}